﻿
var Map_Obj = document.getElementById("map");
var Map_ObjW = Map_Obj.offsetWidth;
var Map_ObjH = Map_Obj.offsetHeight-130;
$('#map').css({
    height: Map_ObjH, width: Map_ObjW
});

var map;
var glVecLayer, glImgLayer, glLabelLayer;   //google相关图层
var tianVecLayer, tianImgLayer, tianLabelLayer;   //天地图相关图层 Vec地图 Img影像 Label标注
var curmaptype;   //底图类型，"vec","img"
var baseMapType, projection = 2;    //底图类型1:tianditu(无偏的),2:球面墨卡托，有偏移； 投影(仅适用于天地图)1:经纬度 2:球面墨卡托
var baseMap = 2;   //1:amap 2:google 3:beijing54
var googleCopyright = "图源：地图数据 2017 Google, 图像 2015 TerraMetrics， CNES/Astrium, DigitalGlobe";
var amapCopyright = "图源：2017 高德 审图号GS(2014)6002号 | 京ICP证 070711号 | 甲测资字11002004";


/**
 * 经纬度转墨卡托
 * @param poi 经纬度
 * @returns {{}}
 * @private
 */
function _getMercator(poi) {//[114.32894, 30.585748]
    var mer = {};
    var x = parseFloat(poi.x);
    var y = parseFloat(poi.y);
    var tmepx = x * 20037508.342787 / 180;
    var tempy = Math.log(Math.tan((90 + y) * Math.PI / 360)) / (Math.PI / 180);
    tempy = tempy * 20037508.342787 / 180;
    mer.x = tmepx;
    mer.y = tempy;
    return mer;

}
/**
 * 墨卡托转经纬度
 * @param poi 墨卡托
 * @returns {{}}
 * @private
 */
function _getLngLat(poi){
    var lnglat = {};
    lnglat.lng = poi.x/20037508.34*180;
    var mmy = poi.y/20037508.34*180;
    lnglat.lat = 180/Math.PI*(2*Math.atan(Math.exp(mmy*Math.PI/180))-Math.PI/2);
    return lnglat;
}


function InitMap() {
    map = new SuperMap.Map("map", {
        controls: [
            new SuperMap.Control.MousePosition(),
           /* new SuperMap.Control.LayerSwitcher({
                id: "SuperMap.Control.LayerSwitcher_SGIS"
            }),*/
            new SuperMap.Control.Navigation({
                dragPanOptions: {
                    enableKinetic: true
                }
            })],
        allOverlays: true, projection: "EPSG:4490" //此处必须设置地图投影且保持与数据投影一致 否则麻点会出不来
    });
    map.minZoom = 8;
    map.maxZoom = 20;
    initBaseControls();
    changeToTianImg();
    //changeToGoogleImg();
    var poi = {
        x:112.98626,
        y:28.25591
    };

    //转换墨卡托坐标时使用
    //var mercator = _getMercator(poi);

    //changeToTianImg();
    map.setCenter(new SuperMap.LonLat(poi.x, poi.y).transform(
        new SuperMap.Projection("EPSG:4490"),
        map.getProjectionObject()), 12);
}

//初始化地图的基本控件，导航、比例尺、缩放
function initBaseControls() {
    var container = map.getSize();
    //地图平移控件
    var panzoombar = new SuperMap.Control.PanZoomBar();
    panzoombar.showSlider = true;
    panzoombar.showCompass = false;
    map.addControl(panzoombar, new SuperMap.Pixel(container.w - 100, container.h - 250));
    map.addControl(new SuperMap.Control.KeyboardDefaults());
    //地图缩放控件
    var navigation = new SuperMap.Control.Navigation({
        dragPanOptions: { enableKinetic: true },
        //屏蔽双击放大事件
        defaultDblClick: function (event) {
            return;
        }
    });
    map.addControl(navigation, new SuperMap.Pixel(container.w - 100, 50));
    //比例尺控件
    map.addControl(new SuperMap.Control.ScaleLine(),
        new SuperMap.Pixel(50, container.h - 70));
}


function initTianLayers() {
    if (glImgLayer == null || glImgLayer == undefined) {
        /*glVecLayer = new SuperMap.Layer.Google("地图", "vec");
        glImgLayer = new SuperMap.Layer.Google("影像", "img");
        glLabelLayer = new SuperMap.Layer.Google("影像标注", "label");*/
        tianVecLayer = new SuperMap.Layer.TDT("地图", "vec");
        tianImgLayer = new SuperMap.Layer.TDT("影像", "img");
        tianLabelLayer = new SuperMap.Layer.TDT("影像标注", "img_label");
    }
    curmaptype = "img";
}


function changeToTianImg() {
    removeAllLayers();
    curmaptype = "img";
    initTianLayers();
    tianVecLayer.isBaseLayer = true;
    tianImgLayer.isBaseLayer = true;
    tianLabelLayer.isBaseLayer = false;
    map.addLayers([tianVecLayer, tianImgLayer, tianLabelLayer]);
    SetMap2D('2');
    baseMap = 2;
    setMapCopyright(baseMap);
}


function initGoogleLayers() {
    if (glImgLayer == null || glImgLayer == undefined) {
        /*glVecLayer = new SuperMap.Layer.Google("地图", "vec");
        glImgLayer = new SuperMap.Layer.Google("影像", "img");
        glLabelLayer = new SuperMap.Layer.Google("影像标注", "label");*/
        glVecLayer = new SuperMap.Layer.Google("地图", "vec");
        glImgLayer = new SuperMap.Layer.Google("影像", "img");
        glLabelLayer = new SuperMap.Layer.Google("影像标注", "label");
    }
    curmaptype = "img";
}

function changeToGoogleImg() {
    removeAllLayers();
    curmaptype = "img";
    initGoogleLayers();
    glVecLayer.isBaseLayer = true;
    glImgLayer.isBaseLayer = true;
    glLabelLayer.isBaseLayer = false;
    map.addLayers([glVecLayer, glImgLayer, glLabelLayer]);
    SetGoogleMap2D('2');
    baseMap = 2;
    setMapCopyright(baseMap);
}
function setMapCopyright(baseMap) {
    if (baseMap == 1) {
        $("#mapCopyright").text(amapCopyright);
    } else if (baseMap == 2) {
        $("#mapCopyright").text(googleCopyright);
    }
}

function removeAllLayers() {
    var length = map.getNumLayers();
    for (var i = 0; i < length; i++) {
        map.removeLayer(map.layers[0]);
    }
}

function SetGoogleMap2D(xh) {
    if (xh == "2") {
      glVecLayer.setVisibility(false);
      glImgLayer.setVisibility(true);
      glLabelLayer.setVisibility(true);
        curmaptype = "vec";
    }
    else {
        tianVecLayer.setVisibility(true);
        tianImgLayer.setVisibility(false);
        tianLabelLayer.setVisibility(false);
        curmaptype = "img";
    }
}


function SetMap2D(xh) {
    if (xh == "2") {
        tianVecLayer.setVisibility(false);
        tianImgLayer.setVisibility(true);
        tianLabelLayer.setVisibility(true);
      /*  glVecLayer.setVisibility(false);
        glImgLayer.setVisibility(true);
        glLabelLayer.setVisibility(true);*/
        curmaptype = "vec";
    }
    else {
        tianVecLayer.setVisibility(true);
        tianImgLayer.setVisibility(false);
        tianLabelLayer.setVisibility(false);
        curmaptype = "img";
    }
}

//设置地图范围
function SetMapBound(ArrLng, ArrLat) {
    if (ArrLng.length > 1) {
        var left = 0, bottom = 0, right = 0, top = 0;
        left = Math.min.apply(null, ArrLng);
        right = Math.max.apply(null, ArrLng);
        bottom = Math.min.apply(null, ArrLat);
        top = Math.max.apply(null, ArrLat);
        var bounds = new SuperMap.Bounds(left, bottom, right, top);
        map.zoomToExtent(bounds, false);
        ArrLng = [];
        ArrLat = [];
    }
    if (ArrLng.length == 1) {
        map.setCenter(new SuperMap.LonLat(ArrLng[0], ArrLat[0]), 10);
    }
}


var strategy = new SuperMap.Strategy.GeoText();
var selectFeature = null;
strategy.style = {
    fontColor: "#FFFFFF",
    fontWeight: "nomal",
    fontSize: "14px",
    fill: false,
    fillColor: "#FFA500",
    fillOpacity: 1,
    stroke: false,
    strokeColor: "#FFA500"
};

// 产业聚集图
var SettingForCircle = {
    codomain: [0, 1000],
    maxR: 50,
    minR: 10,
    circleStyle: { fillOpacity: 0.8 },
    fillColor: "#FFA500",
    circleHoverStyle: { fillOpacity: 1 }
};


var InfoWin = null;
var InfoWin_Json = { con: "", lng: 0, lat: 0, dwbs: 0 };
function ShowInfoWin() {
    CloseInfoWin();
    var lnglat = new SuperMap.LonLat(InfoWin_Json.lng, InfoWin_Json.lat);
    if (InfoWin_Json.dwbs == 1) {
        map.setCenter(lnglat, 15);
    }
    var contentHTML = "<div style='font-size:12px;font-weight:bold;opacity: 0.8; overflow:auto; max-height:400px;max-width:500px;'>";
    contentHTML += InfoWin_Json.con;
    contentHTML += "</div>";
    
    framedCloud = new SuperMap.Popup.FramedCloud(
    "chicken",
    lnglat,
    null,
    contentHTML,
    null,
    true,
    null,
    true
    );

    InfoWin = framedCloud;
    map.addPopup(framedCloud);
}

function CloseInfoWin() {
    if (InfoWin) {
        try {
            InfoWin.hide();
            InfoWin.destroy();
        }
        catch (e) { }
    }
}

var Area_Query_Params = {
    //query_url: "http://cydt.acmr.com.cn:20119/iserver/services/data-cydt4/rest/data",
    query_url: "http://175.6.46.164:8090/iserver/services/data-SGIS_XJXQ/rest/data",

    // query_url:"http://175.6.46.164:8090/iserver/services/map-SGIS_XJXQ/rest",
    dsname: "",
    dtname: "",
    strcode:""
};
var Area_StyleOptions = {
    /*strokeWeight: 3,       //边线的宽度
    fillColor: "#BDC5C0",      //填充颜色
    strokeColor: "#3B9FD3",    //边线颜色。
   strokeStyle: 'solid', //边线的样式，solid或dashed。
    strokeOpacity:1,	   //边线透明度，取值范围0 - 1。
    fillOpacity: 0.6     //填充的透明度，取值范围0 - 1。*/
    strokeColor: "#3B9FD3",
    fillColor: "#BDC5C0",
    strokeWidth: 2,
    fillOpacity: 0.6,
    label: "",
    fontColor: "#FFFFFF",
    fontSize:"12px"
};
var Area_StyleOptions_1 = {
    /*strokeWeight: 3,       //边线的宽度
    fillColor: "#BDC5C0",      //填充颜色
    strokeColor: "#3B9FD3",    //边线颜色。C14829
    fillOpacity: 0.6     //填充的透明度，取值范围0 - 1。*/
    strokeColor: "#3B9FD3",
    fillColor: "#BDC5C0",
    strokeWidth: 2,
    fillOpacity: 0.6,
    label: "",
    fontColor: "#FFFFFF",
    fontSize:"12px"
};
var Area_Layer = new SuperMap.Layer.Vector("区划边界");
var Area_Geo = null;

/*初始化查询区域 Begin*/
function Query_Area() {
    Area_Geo = null;
    var dsname = Area_Query_Params.dsname;
    var dtname = Area_Query_Params.dtname;
    var url = Area_Query_Params.query_url;
    var strcode = Area_Query_Params.strcode;

    var queryParam, queryBySQLParams, queryBySQLService;
    queryParam = new SuperMap.REST.FilterParameter({
        name: dtname + "@" + dsname,
        attributeFilter: strcode
    }),
    queryBySQLParams = new SuperMap.REST.GetFeaturesBySQLParameters({
        queryParameter: queryParam,
        datasetNames: [dsname + ":" + dtname],
        toIndex: 30
    }),
    queryBySQLService = new SuperMap.REST.GetFeaturesBySQLService(url, {
        eventListeners: { "processCompleted": QueryAreaCompleted, "processFailed": processFailed }
    });
    queryBySQLService.processAsync(queryBySQLParams);
}
function QueryAreaCompleted(queryEventArgs) {
    var i, len, feature, result = queryEventArgs.result;
    Dic_Area = [];
    var Areafeas = [];
    var AreaInfo = { id: "", text: "", pid: "", bound: "", xh: 0, geo: 0 };
    var AreaGeo;
    if (result && result.features) {
        Area_Geo = result.features;
        Draw_AreaLayer();
        //for (i = 0, len = Areafeas.length; i < len; i++) {
        //    AreaInfo = { id: "", text: "", pid: "", bound: "", xh: 0 };
        //    AreaInfo.id = Areafeas[i].attributes.CODE;
        //    AreaInfo.text = Areafeas[i].attributes.NAME;
        //    AreaInfo.pid = Areafeas[i].attributes.PCODE;
        //    AreaInfo.bound = Areafeas[i].attributes.BOUND;
        //    AreaInfo.xh = i;
        //    AreaInfo.geo = Areafeas[i].geometry;
        //    Dic_Area.push(AreaInfo);
        //}
    }
}
function processFailed(e) {
    alert(e.error.errorMsg);
}